import React from "react";
import { Tree, Spin } from "antd";
import { connect } from "dva";
// import { equals } from "@cbd/utils";
import styles from "./UserTree.less";

import { openNotificationWithIcon, getOrgName } from "../../utils/comm.js";

const { TreeNode } = Tree;

@connect(({ usertreeSelect, loading }) => ({
  loading,
  usertreeSelectStore: usertreeSelect,
}))
class UserTree extends React.Component {
  constructor(props) {
    super(props);
    this.openNotificationWithIcon = openNotificationWithIcon;
    this.selectData = [];
    this.loadedKeys = [];
    this.selectedKeysInvert = [];
    this.state = {
      treeData: [],
      selectedKeys: [],
    };
  }

  componentDidMount() {
    this.getTreeThis();
    this.getRootOrg();
  }

  componentWillReceiveProps(nextProps) {
    const { checkedKeys } = nextProps;
    const { selectedKeys } = this.state;
    if (checkedKeys && checkedKeys !== selectedKeys) {
      this.setState({
        selectedKeys: checkedKeys,
      });
    }
  }

  componentDidUpdate(prevProps) {
    // 如果数据发生变化，则更新数据
    const { selectedKeys } = this.state;
    if (prevProps.checkedKeys !== selectedKeys) {
      this.setSelectedKeys(prevProps.checkedKeys);
    }
  }

  componentWillUnmount() {}

  setSelectedKeys = (v) => {
    this.setState({
      selectedKeys: v,
    });
  };

  getRootOrg = () => {
    const { dispatch } = this.props;
    if (!dispatch) return;
    dispatch({
      type: "usertreeSelect/getRootOrg",
      payload: {},
    }).then(({ errCode, datas }) => {
      if (errCode !== 0) {
        this.openNotificationWithIcon("error", "", "获取根组织信息失败");
      }
      const newDatas = Array.isArray(datas) ? datas : [datas];
      this.loadedKeys = this.loadedKeys.concat(newDatas);
      this.setState({ treeData: newDatas });
    });
  };

  getSelectData = () => {
    const res = [];
    this.selectData.forEach((item) => {
      if (item.props) {
        const {
          props: { dataRef },
        } = item;
        if (dataRef.code)
          res.push({ code: dataRef.code, name: dataRef.displayName });
      } else if (item.code) {
        res.push(item);
      }
    });
    return res;
  };

  getTreeThis = () => {
    const { getTreeRef } = this.props;
    if (getTreeRef) getTreeRef(this);
  };

  onCheck = (checkedKeys, { checkedNodes }) => {
    this.selectData = checkedNodes;
    this.setState({ selectedKeys: checkedKeys });
    const { checkTreefunction } = this.props;
    if (checkTreefunction) {
      checkTreefunction(checkedKeys, checkedNodes);
    }
  };

  handleLoadData = (treeNode) =>
    new Promise((resolve) => {
      const { dispatch } = this.props;
      const { treeData, selectedKeys } = this.state;
      if (treeNode.props.children) {
        resolve();
        return;
      }
      const orgCode = treeNode.props.dataRef.code;
      const orgName = treeNode.props.dataRef.displayName;
      dispatch({
        type: "usertreeSelect/getChildren",
        payload: { pageNo: 1, pageSize: 1000, orgCode, orgName },
      }).then(({ errCode, uerrCode, uerrMsg, errMsg, datas }) => {
        if (errCode !== 0) {
          this.openNotificationWithIcon(
            "error",
            "",
            errMsg || "获取子组织信息失败",
          );
        }
        if (uerrCode !== 0) {
          this.openNotificationWithIcon(
            "error",
            "",
            uerrMsg || "获取人员信息失败",
          );
        }
        if (datas.length > 0) {
          treeNode.props.dataRef.children = datas;
          // 反显处理
          const loadedSelectedKeys = this.selectedKeysInvert.filter((item) => {
            return datas.some((citem) => citem.code === item);
          });
          const newKeys = [...selectedKeys, ...loadedSelectedKeys];
          this.loadedKeys = this.loadedKeys.concat(datas);
          this.setState({
            treeData: [...treeData],
            selectedKeys: newKeys,
          });
          resolve();
        }
        resolve();
      });
    });

  renderTreeNodes = (data, parentOrgs = []) =>
    data.map((item) => {
      if (item.children) {
        return (
          <TreeNode
            disableCheckbox={!item.isLeaf}
            title={item.displayName}
            key={item.code}
            dataRef={item}
            orgsArr={parentOrgs}
          >
            {this.renderTreeNodes(item.children, parentOrgs.concat(getOrgName(item)))}
          </TreeNode>
        );
      }
      return (
        <TreeNode
          disableCheckbox={!item.isLeaf}
          title={item.displayName}
          key={item.code}
          dataRef={item}
          isLeaf={item.isLeaf}
          orgsArr={parentOrgs}
        />
      );
    });

  render() {
    const { treeData, selectedKeys } = this.state;
    const {
      loading: { effects },
    } = this.props;
    const rootLoading = effects["usertreeSelect/getRootOrg"];
    return (
      <Spin spinning={rootLoading}>
        <div className={styles.user_tree}>
          {treeData.length > 0 && (
            <Tree.DirectoryTree
              checkable
              loadData={this.handleLoadData}
              onCheck={this.onCheck}
              defaultSelectedKeys={selectedKeys}
              defaultCheckedKeys={selectedKeys}
              // onLoad={this.OnTreeLoaded}
              checkedKeys={selectedKeys}
              selectedKeys={selectedKeys}
            >
              {this.renderTreeNodes(treeData)}
            </Tree.DirectoryTree>
          )}
        </div>
      </Spin>
    );
  }
}
export default UserTree;
